﻿using System;
using System.Linq;
using System.Text;
using Caliburn.Core.Metadata;
using Caliburn.PresentationFramework.ApplicationModel;
using Microsoft.Practices.ServiceLocation;
using System.Threading;
using XWord.WPF.ApplicationFramework;
using Luna.WPF.ApplicationFramework;
using XWord.GUI.Presenters.Interface;
using System.Collections;
using System.Windows;
using System.Collections.Specialized;
using System.Windows.Controls;
using Microsoft.Win32;
using System.IO;
using System.Windows.Data;
using XWord.WPF.ApplicationFramework.Threads;
using XWord.Common;
namespace XWord.GUI.Presenters.Fundamental
{
    [Singleton(typeof(ICategoryExplorerPresenter))]
    public partial class CategoryExplorerPresenter : DockingPresenter, ICategoryExplorerPresenter
    {
        private readonly IWindowManager _windowManager;
        private readonly IServiceLocator _serviceLocator;
        public CategoryExplorerPresenter(IServiceLocator entityFactory)
        {
            _serviceLocator = entityFactory;
            _windowManager = entityFactory.GetInstance<IWindowManager>();
            this.DisplayName = "分类";
            //Application.Current.Exit += new ExitEventHandler(Current_Exit);
        }

        void Current_Exit(object sender, ExitEventArgs e)
        {
            BinaryFormatterHelper.Serialize(BinaryFiles.CategoryList, CategoryList);
        }

        protected override void OnInitialize()
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback((object obj) =>
            {
                
                //CategoryList = BinaryFormatterHelper.Deserialize<Hashtable>(BinaryFiles.CategoryList);
            }));
            WordBehavior.WordEventHandler+=new WordEventHandler(WordBehavior_WordEventHandler);
            base.OnInitialize();
        }

        void WordBehavior_WordEventHandler(object sender, WordEventArgs args)
        {
            switch (args.Action)
            {
                case WordAction.Add:
                    break;
                case WordAction.Remove:
                    break;
                case WordAction.SelectedItemChanged:
                    if (!string.IsNullOrEmpty(args.Word.Name))
                        AddMenu(args.Word.Name);
                    break;
                default:
                    break;
            }
        }

        void AddMenu(string word)
        {
            if (this.SelectedItem.Key == null) return;
            var sc = (this.SelectedItem.Value as Hashtable)["List"] as StringCollection;
            if (sc == null || !sc.Contains(word)) return;
            var element = WordExplorerPresenter.AdornerElement.ItemContainerGenerator.ContainerFromItem(word) as FrameworkElement;

            element.ContextMenu.Loaded -= new RoutedEventHandler(ContextMenu_Loaded);
            element.ContextMenu.Closed -= new RoutedEventHandler(ContextMenu_Closed);
            element.ContextMenu.Loaded += new RoutedEventHandler(ContextMenu_Loaded);
            element.ContextMenu.Closed += new RoutedEventHandler(ContextMenu_Closed);
        }

        void ContextMenu_Loaded(object sender, RoutedEventArgs e)
        {
            var target = (sender as ContextMenu);
            var menu = new MenuItem() { Header = "删除分类" };
            menu.Click += new RoutedEventHandler(menu_Click);
            target.Items.Add(menu);
        }

        void menu_Click(object sender, RoutedEventArgs e)
        {
            DeleteWord(WordExplorerPresenter.SelectedItem);

        }

        void ContextMenu_Closed(object sender, RoutedEventArgs e)
        {
            var target = (sender as ContextMenu);
            target.Items.RemoveAt(2);
            target.Closed -= ContextMenu_Closed;
        }

        private Hashtable _categoryList;
        public Hashtable CategoryList
        {
            get { return _categoryList ?? (_categoryList = new Hashtable()); }
            set
            {
                _categoryList = value;
                NotifyOfPropertyChange("CategoryList");
            }
        }

        private DictionaryEntry _selectedItem;
        public DictionaryEntry SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                _selectedItem = value;
                NotifyOfPropertyChange("SelectedItem");
            }
        }

        public void SetCategoryWord(DictionaryEntry SelectedItem)
        {
            var ht = SelectedItem.Value as Hashtable;
            if (ht["List"] != null)
            {
                var list = ht["List"] as StringCollection;
                WordExplorerPresenter.WordList = list.Cast<string>().OrderBy(e=>e).ToObservableCollection();
                //WordExplorerPresenter.SelectedItem = string.Empty;
            }
            else
            {
                WordExplorerPresenter.WordList = null;
            }
            
        }

        public IWordBehavior WordBehavior { get; set; }

        public IWordExplorerPresenter WordExplorerPresenter { get; set; }



        private void Refresh()
        {
            UIThread.BeginInvoke(() =>
            {
                CollectionViewSource.GetDefaultView(CategoryList).Refresh();
            });
        }
    }
}
